import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:photo_manager/photo_manager.dart';
import 'package:video_player/video_player.dart';

import 'video_player_controller.dart';

class VideoPlayerPage extends StatelessWidget {
  final AssetEntity videoFile;
  final List<AssetEntity> videoList;

  VideoPlayerPage({required this.videoFile, required this.videoList});

  final controller = Get.put(PlayerController());

  @override
  Widget build(BuildContext context) {
    // 初始化控制器和视频
    controller.videoList = videoList;
    controller.initializeVideo(videoFile);

    return OrientationBuilder(builder: (context, orientation) {
      return Scaffold(
        body: Obx(() {
          // 检查视频是否初始化
          if (!controller.isInitialized.value) {
            return Center(child: CircularProgressIndicator());
          }

          return orientation == Orientation.portrait
              ? _buildLandscapeLayout() // 竖屏布局
              : _buildPortraitLayout(); // 横屏布局
        }),
      );
    });
  }

  // 横屏布局
  Widget _buildLandscapeLayout() {
    return Stack(
      children: [
        Center(
          child: AspectRatio(
            aspectRatio: controller.videoPlayerController.value.aspectRatio,
            child: VideoPlayer(controller.videoPlayerController),
          ),
        ),
        Positioned(
          top: 10,
          left: 10,
          right: 10,
          child: _buildTopControls(), // 顶部的控制栏
        ),
        Positioned(
          bottom: 10,
          left: 10,
          right: 10,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              _buildProgressControls(), // 进度条和时间显示
              SizedBox(height: 10),
              _buildPlaybackControls(), // 播放控制按钮
            ],
          ),
        ),
      ],
    );
  }

  // 顶部控制按钮：返回、播放列表、设置、旋转、截图、静音
  Widget _buildTopControls() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Row(
          children: [
            IconButton(
              icon: Icon(Icons.arrow_back),
              onPressed: () => Get.back(),
            ),
            IconButton(
              icon: Icon(Icons.playlist_play),
              onPressed: () => showPlaylistDialog(Get.context!),
            ),
          ],
        ),
        Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            IconButton(
              icon: Icon(Icons.settings),
              onPressed: () {
                // 添加设置功能
              },
            ),
            IconButton(
              icon: Icon(Icons.screen_rotation),
              onPressed: () {
                // 添加旋转屏幕功能
              },
            ),
            IconButton(
              icon: Icon(Icons.camera_alt),
              onPressed: () {
                // 添加截图功能
                // controller.captureScreenshot();
              },
            ),
            IconButton(
              icon: Icon(controller.isMuted.value ? Icons.volume_off : Icons.volume_up),
              onPressed: () {
                // 静音功能
                controller.toggleMute();
              },
            ),
          ],
        ),
      ],
    );
  }

  // 播放控制按钮
  Widget _buildPlaybackControls() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [
        IconButton(
          icon: Icon(Icons.skip_previous),
          onPressed: controller.seekToPrevious,
        ),
        Obx(() => IconButton(
              icon: Icon(controller.isPlaying.value ? Icons.pause : Icons.play_arrow),
              onPressed: controller.playPause,
            )),
        IconButton(
          icon: Icon(Icons.skip_next),
          onPressed: controller.seekToNext,
        ),
        IconButton(
          icon: Icon(controller.isFullScreen.value ? Icons.fullscreen_exit : Icons.fullscreen),
          onPressed: controller.toggleFullScreen,
        ),
      ],
    );
  }

  // 进度条和时间显示
  Widget _buildProgressControls() {
    return Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Obx(() => Text(_formatDuration(controller.currentPosition.value))),
            Expanded(
              child: VideoProgressIndicator(
                controller.videoPlayerController,
                allowScrubbing: true,
              ),
            ),
            Obx(() => Text(_formatDuration(controller.totalDuration.value))),
          ],
        ),
      ],
    );
  }

  // 竖屏布局
  Widget _buildPortraitLayout() {
    return Center(
      child: Column(
        children: [
          AspectRatio(
            aspectRatio: controller.videoPlayerController.value.aspectRatio,
            child: VideoPlayer(controller.videoPlayerController),
          ),
          _buildControls(),
        ],
      ),
    );
  }

  // 格式化时间
  String _formatDuration(Duration duration) {
    String twoDigits(int n) => n.toString().padLeft(2, '0');
    final hours = twoDigits(duration.inHours);
    final minutes = twoDigits(duration.inMinutes.remainder(60));
    final seconds = twoDigits(duration.inSeconds.remainder(60));
    return hours != "00" ? "$hours:$minutes:$seconds" : "$minutes:$seconds";
  }

  // 播放列表提示框列表展示
  void showPlaylistDialog(BuildContext context) {
    showModalBottomSheet(
      context: context,
      builder: (context) => ListView.builder(
        itemCount: controller.videoList.length,
        itemBuilder: (context, index) {
          final video = controller.videoList[index];
          return ListTile(
            title: Text(video.title ?? 'Video $index'),
            onTap: () {
              controller.currentIndex.value = index;
              controller.initializeVideo(video);
              Get.back();
            },
          );
        },
      ),
    );
  }

  Widget _buildControls() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.end,
      children: [
        // 当前时间、进度条、总时长
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
          child: Obx(() => Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  // 左侧显示当前播放时间
                  Text(
                    _formatDuration(controller.currentPosition.value),
                    style: TextStyle(color: Colors.white),
                  ),
                  // 进度条
                  Expanded(
                    child: VideoProgressIndicator(
                      controller.videoPlayerController,
                      allowScrubbing: true,
                      colors: VideoProgressColors(
                        playedColor: Colors.red,
                        bufferedColor: Colors.white70,
                        backgroundColor: Colors.grey,
                      ),
                    ),
                  ),
                  // 右侧显示总时长
                  Text(
                    _formatDuration(controller.totalDuration.value),
                    style: TextStyle(color: Colors.white),
                  ),
                ],
              )),
        ),
        // 播放控制按钮
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            IconButton(
              icon: Icon(Icons.skip_previous, color: Colors.white),
              onPressed: controller.seekToPrevious,
            ),
            Obx(() => IconButton(
                  icon: Icon(
                    controller.isPlaying.value ? Icons.pause : Icons.play_arrow,
                    color: Colors.white,
                  ),
                  onPressed: controller.playPause,
                )),
            IconButton(
              icon: Icon(Icons.skip_next, color: Colors.white),
              onPressed: controller.seekToNext,
            ),
            IconButton(
              icon: Icon(Icons.fullscreen, color: Colors.white),
              onPressed: controller.toggleFullScreen, // 切换全屏按钮
            ),
          ],
        ),
        SizedBox(height: 10), // 控制按钮与底部的间距
      ],
    );
  }
}
